<template>
  <layout v-loading="loading">
    <div class="order-info bw">
      <!-- 顶部步骤条 -->
      <div class="w pad-20-0">
        <el-row>
          <el-col :span="12">
            <router-link :to="{ name: 'index' }">
              <el-image style="width: 134px; height: 42px" src="/images/logo.png" />
              <el-image src="/images/order/purchase.png" />
            </router-link>
          </el-col>
          <el-col :span="12">
            <div class="order-steps">
              <el-steps :active="2" :space="200" finish-status="success" align-center>
                <el-step title="1.我的购物车" />
                <el-step title="2.填写核对订单信息" />
                <el-step title="3.成功提交订单" />
              </el-steps>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 标题 -->
      <div class="w pad-20-0 order-title">
        <span class="fs-16">填写并核对订单信息</span>
      </div>
      <!-- 订单详细信息 -->
      <div class="w pad-10 order-detail">
        <!-- 收货人信息 -->
        <div class="detail-item">
          <div class="detail-item-title clearfix">
            <div class="fl">
              <strong class="fs-16">收货人信息</strong>
            </div>
            <div class="fr">
              <el-link :underline="false" @click="maintainReceiveAddressEvent('add')">新增收货人信息</el-link>
            </div>
          </div>
          <div class="detail-item-content">
            <div class="consignee-box">
              <el-scrollbar :class="(order.address.expand ? 'expand-more ' : '') + 'c-scroll'" max-height="168px">
                <div class="c-content">
                  <ul class="c-list" :style="{ top: `-${order.address.selectTop}px` }">
                    <li
                      @mouseenter.self="mouseenterConsigneeLiEvent"
                      @mouseleave.self="mouseleaveConsigneeLiEvent"
                      v-for="(address, idx) in order.address.dataList" :key="idx"
                      class="clearfix">
                      <div
                        @click="selectConsigneeItemEvent($event, address)"
                        @mouseenter.self="mouseenterConsigneeItemEvent"
                        @mouseleave.self="mouseleaveConsigneeItemEvent"
                        :class="(address.id === order.address.selectedId ? 'item-selected ' : '') + 'c-item clearfix'">
                        <span>{{ address.name }}</span>
                        <b></b>
                      </div>
                      <div class="addr-detail">
                        <span class="addr-name">{{ address.name }}</span>
                        <span class="addr-info">{{ address.province }} {{ address.city }} {{ address.region }} {{ address.detailAddress }}</span>
                        <span class="addr-tel">{{ address.phone }}</span>
                        <span v-if="address.isDefault === 1" class="addr-default">默认地址</span>
                      </div>
                      <div class="op-btns">
                        <el-link
                          type="primary" :underline="false"
                          @click="maintainReceiveAddressEvent('update', address.id)">
                          编辑
                        </el-link>
                        <el-link
                          v-if="address.id !== order.address.selectedId"
                          @click="deleteReceiveAddressEvent(address.id)"
                          type="primary" :underline="false">
                          删除
                        </el-link>
                      </div>
                    </li>
                  </ul>
                </div>
              </el-scrollbar>
              <div class="c-more">
                <el-link :underline="false" @click="() => order.address.expand = !order.address.expand">
                  更多收货地址
                  <icon-svg :name="(order.address.expand ? 'arrow-up' : 'arrow-down')"></icon-svg>
                </el-link>
              </div>
            </div>
          </div>
        </div>
        <div class="order-line"></div>
        <!-- 支付方式 -->
        <div class="detail-item">
          <div class="detail-item-title clearfix">
            <div class="fl">
              <strong class="fs-16">支付方式</strong>
            </div>
          </div>
          <div class="detail-item-content pad-10 clearfix">
            <div class="fl">
              <el-radio-group v-model="order.payment" size="large" fill="#f0f0f0">
                <el-radio :label="0" :border="true" disabled>货到付款</el-radio>
                <el-radio :label="1" :border="true">在线支付</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
        <div class="order-line"></div>
        <!-- 送货清单 -->
        <div class="detail-item">
          <div class="detail-item-title clearfix">
            <div class="fl">
              <strong class="fs-16">送货清单</strong>
            </div>
          </div>
          <div class="detail-item-content pad-10">
            <div class="sku-table">
              <el-table
                element-loading-text="拼命加载中"
                :data="order.skuList"
                :header-cell-style="{ background: '#f8f8f8', color: '#999', }"
              >
                <el-table-column prop="image" align="center" width="90" label="商品">
                  <template #default="scope">
                    <router-link target="_blank" :to="`/item/${scope.row.id}`">
                      <el-image style="width: 80px; height: 80px" fit="fill" :src="scope.row.image" />
                    </router-link>
                  </template>
                </el-table-column>
                <el-table-column prop="title" header-align="left" align="left">
                  <template #default="scope">
                    <router-link class="s-title" target="_blank" :to="`/item/${scope.row.id}`">
                      {{ scope.row.title }}
                    </router-link>
                  </template>
                </el-table-column>
                <el-table-column prop="props" header-align="left" align="left" width="140" show-overflow-tooltip />
                <el-table-column prop="price" header-align="right" align="right" width="120" label="单价">
                  <template #default="scope">
                    <span>{{ amountCNYFormatter(scope.row.price) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="count" header-align="right" align="right" width="140" label="数量" />
                <el-table-column prop="amount" header-align="right" align="right" width="140" label="小计">
                  <template #default="scope">
                    <strong>{{ amountCNYFormatter(scope.row.amount) }}</strong>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="order-line"></div>
        <!-- 使用优惠/礼品卡/抵用 -->
        <div class="detail-item">
          <div class="detail-item-title clearfix">
            <div class="fl">
              <strong class="fs-16">使用优惠/礼品卡/抵用</strong>
              <icon-svg name="arrow-down" />
              <!-- <icon-svg name="arrow-up" /> -->
            </div>
          </div>
          <div class="detail-item-content pad-10 clearfix">
            <el-tabs type="border-card">
              <el-tab-pane label="优惠券">
                <el-tabs v-model="data.tab.coupon.active">
                  <el-tab-pane label="商品优惠券" name="product">
                    <el-row class="coupon-box">
                      <el-col v-for="(coupin, idx) in order.coupinList" :key="idx" :span="6">
                        <div class="coupon-item">
                          <div :class="coupinClass(coupin)">
                            <div class="c-msg">
                              <div class="c-top"></div>
                              <div class="c-price">
                                <em> ￥{{ coupin.price }} </em>
                              </div>
                              <div class="c-limit">
                                <span>{{ coupin.limit }}</span>
                              </div>
                              <div class="c-expiration">
                                <span>{{ coupin.expiration }}</span>
                              </div>
                            </div>
                            <div class="c-type">
                              <span v-for="(tn, tidx) in coupin.type" :key="tidx"> [{{ tn }}] </span>
                            </div>
                          </div>
                          <div class="c-info">
                            <icon-svg name="prompt" />
                            <span>&nbsp;{{ coupin.info }}</span>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                    <div class="coupon-schema">
                      <span>金额抵用</span>
                      <em>￥0.00</em>
                      <span> 使用优惠券1张，优惠5.00元 | 使用运费券1张，抵用运费6.00元 </span>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="运费劵" name="freight"> Config </el-tab-pane>
                  <el-tab-pane label="优惠码兑换" name="conversion"> Role </el-tab-pane>
                </el-tabs>
              </el-tab-pane>
              <el-tab-pane label="礼品卡">
                <el-tabs v-model="data.tab.present.active" class="demo-tabs">
                  <el-tab-pane label="可用" name="available"> User </el-tab-pane>
                  <el-tab-pane label="不可用" name="disabled"> Config </el-tab-pane>
                  <el-tab-pane label="添加礼品卡" name="add"> Role </el-tab-pane>
                </el-tabs>
              </el-tab-pane>
              <el-tab-pane label="领货码">
                <el-tabs v-model="data.tab.consignment.active" class="demo-tabs">
                  <el-tab-pane label="可用" name="available"> User </el-tab-pane>
                  <el-tab-pane label="不可用" name="disabled"> Config </el-tab-pane>
                  <el-tab-pane label="添加领货码" name="add"> Role </el-tab-pane>
                </el-tabs>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <!-- 订单概要 -->
      <div class="w pad-20-0 order-summary">
        <div class="list clearfix">
          <em class="fr" style="width: 100px; text-align: right">￥89.00</em>
          <span class="fr">总商品金额：</span>
        </div>
        <div class="list clearfix">
          <em class="fr" style="width: 100px; text-align: right">￥89.00</em>
          <span class="fr">运费：</span>
        </div>
        <div class="list clearfix">
          <em class="fr" style="width: 100px; text-align: right">￥89.00</em>
          <span class="fr">返现：</span>
        </div>
      </div>
      <div class="w pad-10" style="background-color: #f4f4f4; border-top: 1px solid #e6e6e6">
        <div class="list clearfix">
          <em class="fr fs-16 red" style="width: 100px; text-align: right; font-style: normal"> ￥89.00 </em>
          <span class="fr">应付总额：</span>
        </div>
        <div class="list clearfix">
          <span class="fr"> {{ postToAddress }} </span>
        </div>
      </div>
      <!-- 订单底部 -->
      <div class="w pad-20-0 order-footer clearfix">
        <el-button class="fr" type="danger" size="large">提交订单</el-button>
      </div>
    </div>
    <!-- 会员收货地址维护 -->
    <receive-address-add-or-update v-if="order.address.visible" ref="receiveAddressAddOrUpdateRef" @updateReceiveAddressData="updateReceiveAddressData" />
  </layout>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import http from "@/utils/httpRequest.js";
import { addElementClassName, removeElementClassName, amountCNYFormatter } from "@/utils";

import "@/assets/scss/modules/order.scss";
import { ElMessageBox } from "element-plus";
import Layout from "@/views/commons/layout/index.vue";
import ReceiveAddressAddOrUpdate from "@/views/modules/member/receive-address-add-or-update.vue";

// 数据加载状态
const loading = ref(true);

const data = reactive({
  tab: {
    coupon: {
      active: "product",
    },
    present: {
      active: "available",
    },
    consignment: {
      active: "available",
    },
  },
});

// 订单相关数据
const order = reactive({
  // 商品列表
  skuList: [],
  // 优惠卷列表
  coupinList: [],
  // 地址相关信息
  address: {
    // 地址列表
    dataList: [],
    // 选中地址ID
    selectedId: undefined,
    // 收货人选中 top 属性
    selectTop: 0,
    // 更多展开标志
    expand: false,
    // 收货维护窗口是否显示
    visible: false,
  },
  // 支付方式
  payment: 1,
  // 请求令牌
  token: '',
});

// 邮寄到
const postToAddress = computed(() => {
  let sl = order.address.dataList.filter(item => item.id === order.address.selectedId);
  if (sl.length <= 0) {
    return '';
  }
  let address = sl[0];
  return `寄送至：${address.province} ${address.city} ${address.region} ${address.detailAddress} 收货人：${address.name} ${address.phone}`;
});

// 收货地址维护弹窗引用
const receiveAddressAddOrUpdateRef = ref();

// 组件挂载完成后执行
onMounted(() => {
  loadOrderData();
  // loadCouponData();
});

// 加载订单数据
const loadOrderData = () => {
  loading.value = true;
  http
    .get({
      url: "/order/info",
    })
    .then(({ data }) => {
      if (http.success(data)) {
        let body = data.body;
        // 初始化请求令牌
        order.token = body.token;
        // 初始化商品列表
        order.skuList = body.skuList || [];
        // 初始化收货地址列表
        order.address.dataList = body.addressList || [];
        // 默认选中的地址ID
        let mreddress = order.address.dataList.filter(item => item.isDefault === 1);
        if (mreddress.length > 0) {
          order.address.selectedId = mreddress[0].id;
        } else {
          order.address.selectedId = order.address.dataList.length > 0 ? order.address.dataList[0].id : undefined;
        }
        // 计算收货人列表样式
        computedConsigneeListStyle();
      }
      loading.value = false;
    });
};

// 计算收货人列表样式
const computedConsigneeListStyle = () => {
  let idx = order.address.dataList.findIndex(item => item.id === order.address.selectedId);
  order.address.selectTop = (idx < 0 ? 0 : idx) * 36;
};

// 选中收货人
const selectConsigneeItemEvent = (event, address) => {
  order.address.selectedId = address.id;
  computedConsigneeListStyle();
  order.address.expand = false;
};

// 收货人鼠标移上事件
const mouseenterConsigneeItemEvent = (event) => {
  addElementClassName(event.currentTarget, "item-hover");
};

// 收货人鼠标移出事件
const mouseleaveConsigneeItemEvent = (event) => {
  removeElementClassName(event.currentTarget, "item-hover");
};

const mouseenterConsigneeLiEvent = (event) => {
  addElementClassName(event.currentTarget, "c-li-hover");
};

const mouseleaveConsigneeLiEvent = (event) => {
  removeElementClassName(event.currentTarget, "c-li-hover");
};

// 新增
const maintainReceiveAddressEvent = async (type, id = '') => {
  order.address.visible = true;
  await nextTick();
  receiveAddressAddOrUpdateRef.value.initForm(type, id);
};

// 反写修改的地址信息
const updateReceiveAddressData = (data) => {
  if (!data) {
    return;
  }
  let list = order.address.dataList.filter(item => item.id === data.id);
  // 如果能匹配到数据就修改
  if (list.length > 0) {
    list.forEach(item => {
      for (let key in data) {
        item[key] = data[key];
      }
    });
  }
  // 否则新增
  else {
    order.address.dataList.push(data);
  }
  // 选中新增或者修改的地址
  order.address.selectedId = data.id;
  computedConsigneeListStyle();
};

// 删除指定地址信息
const deleteReceiveAddressEvent = (receiveAddressId) => {
  ElMessageBox
      .confirm(`确定要进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        http
          .instance({
            url: http.adornUrl('/member/receive-address/delete'),
            method: "post",
            data: http.adornData([ receiveAddressId ], false),
          })
          .then(({ data }) => {
            if (http.success(data)) {
              let idx = order.address.dataList.findIndex(item => item.id === receiveAddressId);
              order.address.dataList.splice(idx, 1);
              computedConsigneeListStyle();
            }
          });
      })
      .catch(()=>{});
};

// 加载优惠卷数据
const loadCouponData = () => {
  http
    .post({
      url: "/coupon/info",
    })
    .then(({ data }) => {
      if (http.success(data)) {
        order.coupinList = data.body;
      }
    });
};

// 优惠卷状态样式
const coupinClass = (coupin) => {
  return {
    "c-detail": true,
    "c-active": coupin.status === "1" ? true : false,
    "c-disable": coupin.status === "3" ? true : false,
  };
};
</script>
